using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class GridNumbers : UIBehaviour
{

    public TMP_Text textPrefab;
    [Space]
    [Range(0, 100)]
    public int width = 9;
    [Range(0, 100)]
    public int height = 9;
    
    private TMP_Text[,] cells
    {
        get
        {
            if (m_cells == null) InstantiateCells();
            return m_cells;
        }
    }
    private TMP_Text[,] m_cells = null;

    private RectTransform rectTransform
    {
        get
        {
            if (m_rectTransform == null)
            {
                m_rectTransform = GetComponent<RectTransform>();
            }
            return m_rectTransform;
        }
    }
    private RectTransform m_rectTransform;

    public void ShowCell(int x, int y, int number)
    {
        cells[x, y].gameObject.SetActive(true);
        cells[x, y].text = number.ToString();
    }

    public void HideCell(int x, int y)
    {
        cells[x, y].gameObject.SetActive(false);
    }

    public bool IsCellVisible(int x, int y)
    {
        return cells[x, y].gameObject.activeSelf;
    }

    protected override void OnRectTransformDimensionsChange()
    {
        ResetCellPositions();
    }

    private void InstantiateCells()
    {
        m_cells = new TMP_Text[width, height];

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                var cell = Instantiate(textPrefab, rectTransform);
                cell.gameObject.SetActive(false);
                cells[x, y] = cell;
            }
        }
    }

    private void ResetCellPositions()
    {
        var cellSize = rectTransform.rect.size;
        cellSize.x /= width;
        cellSize.y /= height;

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                cells[x, y].rectTransform.sizeDelta = cellSize;
                cells[x, y].rectTransform.anchoredPosition = new Vector2(x * cellSize.x, y * cellSize.y);
            }
        }
    }
}
